<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Wechat extends CI_Controller {

	public function __construct(){
        parent::__construct();
        $this->load->library('CI_Wechat');
    }

    /**
     * 微信-服务器配置
     * @return [type] [description]
     */
    public function service(){
		$this->ci_wechat->valid();
		$type = $this->ci_wechat->getRev()->getRevType();
		switch($type) {
			case 'text':
				// $content = $this->ci_wechat->getRev()->getRevContent();
				// if(strtolower(trim($content))=='setop'){
				// 	$this->ci_wechat->text("呵呵")->reply();
				// }
				break;
			case 'event'://点击事件
				$this->eventHandle();
				break;
			case 'image':
				break;
			default:
				break;
		}

    }

    /**
     * 事件处理
     * @return [type] [description]
     */
    private function eventHandle(){
    	$event = $this->ci_wechat->getRev()->getRevEvent();
		switch($event['event']) {
			case "CLICK"://点击事件
				switch($event['key']) {
					case "KEY_WCP_SERVICE"://获取在线客服信息
							$this->ci_wechat->text("加入官方服务QQ群:144950915最新动态即时沟通!")->reply();
							exit;
							break;
					default:
							break;
				}
				break;
			case 'SCAN'://扫描带参数二维码
				$this->eventScan($event['key']);
				break;
			case 'subscribe'://订阅送体验券
				$keyArr = explode('_',$event['key']);
				$this->eventScan($keyArr[1]);
				break;
			default:
					break;
		}
	}

	 /**
     * 扫描带参数二维码
     * @return [type] [description]
     */
    private function eventScan($master){
		$openid		= $this->ci_wechat->getRev()->getRevFrom();
		$ip			= get_ip();
		$datetime	= date('Y-m-d H:i:s');
		$this->load->library('Referrals');
		$logData = array(
			'master'		=> $master,
			'openid'		=> $openid,
			'ip'			=> $ip,
			'create_time'	=> $datetime,
		);
		writeWXFile($logData);
		$this->referrals->addScanLog($logData);
	}

    /**
     * 创建微信菜单
     * @return [type] [description]
     */
    public function createMenu(){
    	$newMenuArr =  array(
			"button"=>
				array(
					array('type'=>'click','name'=>'微盘介绍','key'=>'KEY_WCP_INTRO',
						"sub_button"=>array(
							array('type'=>'view','name'=>'交易规则','url'=>'https://720quan.com/about/rules'),
						)
					),
					array('type'=>'click','name'=>'会员服务','key'=>'KEY_WCP_VIP',
						"sub_button"=>array(
							array('type'=>'view','name'=>'大赛动态','url'=>'https://720quan.com/about/intro'),
							array('type'=>'view','name'=>'经纪人','url'=>$this->ci_wechat->getOauthRedirect('https://720quan.com/invite/callback','sfc32lSdj45dfo2sdd23GdKLm')),
							array('type'=>'click','name'=>'官方QQ群','key'=>'KEY_WCP_SERVICE'),
						)
					),
					array('type'=>'view','name'=>'进入微盘','url'=>$this->ci_wechat->getOauthRedirect('https://720quan.com/wechat/callback','sfc32lSdj45dfo2sdd23GdKLm')),
				)
		);
		// var_dump($newMenuArr);
		$result = $this->ci_wechat->createMenu($newMenuArr);
		if($result){
			die("创建菜单成功！");
		}else{
			die("创建菜单失败！");
		}
    }

    /**
     * 微信网页授权后返回code
     * @return function [description]
     */
	public function callback(){
		$get = $this->input->get();
		$code = $get['code'];
		$state = $get['state'];
		$redirect = isset($get['redirect'])?"/".$get['redirect']:'/';
		if($state!='sfc32lSdj45dfo2sdd23GdKLm') die('系统错误[10000]！');
		writeDebug('['.date('Y-m-d H:i:s').'] get='.var_export($get,true), "callback");
		$data = $this->ci_wechat->getOauthAccessToken($code);
		writeDebug('['.date('Y-m-d H:i:s').'] data='.var_export($data,true), "callback");
		if(!$data)  die('系统错误[10001]！');
		$openid = $data['openid'];
		$oauthUserInfo = $this->ci_wechat->getOauthUserinfo($data['access_token'],$openid);

		//检查是否已经注册
		$this->load->model('user_model');
		$platform = $this->config->item('platform');//平台
		$whereArr = array(
        	'platform' => $platform,//平台
        	'openid' => $openid,
        );
		$userData = $this->user_model->getUserInfoByMulti($whereArr,true);

		$this->load->library('session');
		$sessid = $this->session->session_id;

		//链接redis
		$this->load->driver('cache');
		$this->cache->redis->is_supported();
		$this->cache->redis->getClient()->set("$platform|WechatCallback|$sessid",$openid);
		$this->cache->redis->getClient()->expire("$platform|WechatCallback|$sessid",43200);

		$_SESSION['openid'] = $openid;
		if(empty($userData)){//没有注册，跳转到注册页面
			if($openid=='oYUCkswy39ISm6KOYsUA165UlKWY1'){
				$this->setTestOP("$platform|WechatCallback|$sessid",$openid);
				redirect("https://test.2800.com/?reg=1&redirect=".$redirect);
			}else{
				redirect(base_url()."?reg=1&redirect=".$redirect);
			}
		}else{//已经注册直接跳转到首页
			$data = array(
	            'nickname' => $oauthUserInfo['nickname']
	        );
	        $whereArr = array(
	            'platform' => $platform,//平台
        		'openid' => $openid,
	        );
	        $rs = $this->user_model->updateUser($data,$whereArr);
	        if($userData['login_flag']==1){//，免密码登陆
	        	$uid = $userData['uid'];
        		$cooper = $this->config->item('cooper');

	        	$this->load->library('passPort');
		        $this->passport->setPlatform($platform);
		        $this->passport->setCooper($cooper);
	        	//是否禁止帐号重复登录
	            if($userData['online_flag']==1){
	                $onlineArr = $this->passport->checkOnline($uid);
	                if(!empty($onlineArr)) foreach($onlineArr as $items){
	                    $this->passport->kickOffline($items['skey']);
	                }
	            }
	            $randPass = md5($this->passport->makeRandPassword());//取得随机密码[用于检验cookie中所存加密字符串正确性]
	            // $this->passport->setExpire($userInfo['cache_expire']);//设置在线误操作过期时间
	            $this->passport->saveOnlineInfo($uid, $randPass);
	            //提出已经超时的用户
	            $this->passport->deleteOverTime();
	            $this->passport->setCookie('wcp_openid',$openid);

	             /***********登录记录LOG Start************/
	            $ip = get_ip();
	            $system = getSystem();
	            $browser = getBrowser();
	            $datetime = date('Y-m-d H:i:s');
	            $loginLog   =   array(
	                    'uid' => $uid,
	                    'cooper' => $cooper,
	                    'comefrom' => 2,//1pc 2手机
	                    'system' => $system,
	                    'browser' => $browser,
	                    'ip' => $ip,
	                    'platform' => $platform,
	                    'create_time' => $datetime,
	            );
	            $this->user_model->addLoginLog($loginLog);
	            /***********登录记录LOG End************/
	        }
	        if($openid=='oYUCkswy39ISm6KOYsUA165UlKWY1'){
	        	$this->setTestOP("$platform|WechatCallback|$sessid",$openid);
				redirect("https://test.2800.com/?redirect=".$redirect);
			}else{
				redirect(base_url()."?redirect=".$redirect);
			}
		}
	}

	public function shareCallback(){
		$get = $this->input->get();
		$code = $get['code'];
		$state = $get['state'];
		$masterOpenid = $get['openid'];
		writeDebug('['.date('Y-m-d H:i:s').'] get='.var_export($get,true), "shareCallback");

		$this->load->model('user_model');
		$whereArr = array(
        	'platform' => 1,//平台
        	'openid' => $masterOpenid,
        );
		$masterUserData = $this->user_model->getUserInfoByMulti($whereArr);
		if(empty($masterUserData)){
			writeDebug('['.date('Y-m-d H:i:s').'] 分享master没有注册['.$masterOpenid.']', "shareCallback");
			die;
		}
		$master = $masterUserData['uid'];
		$data = $this->ci_wechat->getOauthAccessToken($code);
		if(!$data){
			writeDebug('['.date('Y-m-d H:i:s').'] 分享数据错误['.$code.']', "shareCallback");
			die;
		}
		$slave = $data['openid'];

		$ip			= get_ip();
		$datetime	= date('Y-m-d H:i:s');
		$this->load->library('Referrals');
		$logData = array(
			'master'		=> $master,
			'openid'		=> $slave,
			'ip'			=> $ip,
			'create_time'	=> $datetime,
		);
		writeWXFile($logData);
		$this->referrals->addScanLog($logData);

		redirect('http://mp.weixin.qq.com/s?__biz=MzIzMTM5ODk4MQ==&mid=100000009&idx=1&sn=0fb8c2caaee8bfd8cf291e6f46b38b8c&scene=0');

		// $whereArr = array(
  //       	'platform' => 1,//平台
  //       	'openid' => $slave,
  //       );
		// $slaveUserData = $this->user_model->getUserInfoByMulti($whereArr);

		// $platform = $this->config->item('platform');//平台
		// $this->load->library('session');
		// $sessid = $this->session->session_id;
		// //链接redis
		// $this->load->driver('cache');
		// $this->cache->redis->is_supported();
		// $this->cache->redis->getClient()->set("$platform|WechatCallback|$sessid",$slave);
		// $this->cache->redis->getClient()->expire("$platform|WechatCallback|$sessid",43200);
		// if(empty($slaveUserData)){//没有注册，跳转到注册页面
		// 	redirect(base_url()."?reg=1&redirect=".$redirect);
		// }else{//已经注册直接跳转到首页
		// 	redirect(base_url()."?redirect=".$redirect);
		// }
	}

	/**
	 * 设置测试账号跳转到test.2800.com
	 */
	private function setTestOP($key,$val){
		$redis = new Redis();
		$redis->connect('115.29.241.200',6379,0);
		$redis->select(3);
		$rs = $redis->set($key,$val);
	}


}
